package com.itheima.ws;

import com.alibaba.fastjson.JSON;
import com.itheima.config.GetHttpSessionConfig;
import com.itheima.pojo.Message;
import com.itheima.utils.MessageUtil;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/chat", configurator = GetHttpSessionConfig.class)
@Component
public class ChatEndpoint {

    private static final Map<String, Session> onLineUsers = new ConcurrentHashMap<>();
    private HttpSession httpSession;

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        //1. 将session进行保存
        this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        String user = (String) httpSession.getAttribute("user");
        onLineUsers.put(user, session);
        //2. 广播消息，需要将所有在线的用户推送给所有的用户
        String message = MessageUtil.getMessage(true, null, "open" , getFriends());
        broadcastAllUsers(message);
    }

    public Set<String> getFriends() {
        return onLineUsers.keySet();
    }

    private void broadcastAllUsers(String message) {
        try {
            // 遍历map集合
            Set<Map.Entry<String, Session>> entries = onLineUsers.entrySet();
            for (Map.Entry<String, Session> entry: entries) {
                // 获取到所有用户对应的session对象
                Session session = entry.getValue();
                // 发送消息
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message) {
        try {
            // 将消息推送给指定的用户
            Message msg = JSON.parseObject(message, Message.class);
            System.out.println(msg);
            // 获取 消息接收方的用户名
            String toName = msg.getToName();
            String mess = msg.getMessage();
            // 获取消息接收方用户对象的session对象
            Session session = onLineUsers.get(toName);
            String user = (String) httpSession.getAttribute("user");
            String msg1 = MessageUtil.getMessage(false, user,null, mess);
            session.getBasicRemote().sendText(msg1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session) {
        // 1.从onlineUsers中剔除当前用户的session对象
        String user = (String) httpSession.getAttribute("user");
        onLineUsers.remove(user);
        // 2.通知其他所有的用户，当前用户下线了
        String message = MessageUtil.getMessage(true, null, "close", user);
        broadcastAllUsers(message);
    }

}
